﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace DigitalSolutionLibrary.Security
{
    public class TripleDES
    {
        private static readonly string KEY = "HuynhTh@nhDuHuynhTh@nhDu";

        private TripleDES()
        {
        }

        /// <summary>
        /// Encrypt a string
        /// </summary>
        /// <param name="strToEncrypt"></param>
        /// <returns></returns>
        public static string Encryption(string strToEncrypt)
        {
            if (strToEncrypt == null)
                return String.Empty;
            
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(strToEncrypt);
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(KEY);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// Descrypt a string
        /// </summary>
        /// <param name="strToDecrypt"></param>
        /// <returns></returns>
        public static string Decryption(string strToDecrypt)
        {
            if (strToDecrypt == null || strToDecrypt == String.Empty)
                return String.Empty;

            byte[] toEncryptArray = Convert.FromBase64String(strToDecrypt);
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(KEY);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}
